package compiler.ast;

import java.io.PrintStream;
import java.util.ArrayList;

import compiler.tac.BasicBlock;
import compiler.tac.ThreeAddressCode;
import compiler.tac.Instruction.Operator;

public class Expression implements Factor {
	ArrayList<Term> children;
	int codeId = -1;
	public Expression(Term child) {
		children = new ArrayList<Term>();
		children.add(child);
	}
	
	public void addTerm(Term t) {
		children.add(t);
	}

	public void printDotFormat(PrintStream out, String node) {
		String firstNode;
		if (children.size() == 1) {
			firstNode = node;
		} else {
			firstNode = node+0;
			String leftChild = firstNode;
			for (int i = 1; i < children.size(); i++) {
				String rightChild = node+i;
				String oprtNode = (i == children.size()-1) ? node : node+"pm"+i;
				out.println(oprtNode+" [label=\""+children.get(i).getSign()+"\"];");
				out.println(oprtNode+"->"+leftChild+";");
				out.println(oprtNode+"->"+rightChild+";");
				children.get(i).printDotFormat(out, rightChild);
				leftChild = oprtNode;
			}
		}
		children.get(0).printDotFormat(out, firstNode);
	}
	
public String toThreeAddressCode(ThreeAddressCode tac, BasicBlock prev){
		// TODO Auto-generated method stub
		String temp1 = null,temp2 = null;
		
		for(int i = 0; i < children.size(); i ++)
		{
	
			if(i == 0)
			{
				temp1 = children.get(i).toThreeAddresscode(tac, prev, true);
			}
			else 
			{
				temp2 = tac.getTempVar();
				String tmp1 = children.get(i).toThreeAddresscode(tac, prev, false);
				if(children.get(i).sign =='+')
					prev.addBinaryInstruction(Operator.Add, temp2, temp1, tmp1);
				else 
					prev.addBinaryInstruction(Operator.Sub, temp2, temp1, tmp1);
				temp1 = temp2;
			}
		}
		return temp1;
	}
}
